package com.jl.basicframework.utils.dataProcessingUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Base64;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @author 作者：姜澜
 * 时间：2020/5/19
 * 简述：数据格式转换工具
 * 邮箱：31679104@qq.om
 */
public class FormatUtils {


    /**
     * Map转JSON数据
     */
    public static <T> String getJSON(Map<String, T> map) {
        return JSONObject.toJSONString(map);
    }


    /**
     * List转JSON数据
     */
    public static <T> String listToJSON(List<T> list) {
        return JSONObject.toJSON(list).toString();
    }

    /**
     * JSON转RequestBody类型数据
     */
    public static RequestBody getRequestBody(String json) {
        return RequestBody.create(MediaType.parse("application/json")
                , JSON.parseObject(json).toJSONString());
    }

    /**
     * Array转RequestBody类型数据
     */
    public static RequestBody getRequestBody(String json, boolean f) {
        return RequestBody.create(MediaType.parse("application/json")
                , JSONObject.parseArray(json).toJSONString());
    }

    /**
     * JSON转Bean
     */
    public static <T> T getObject(String json, Class<T> zClass) {

        return JSONObject.parseObject(json, zClass);
    }

    /**
     * 验证JSON是否存在传入的字段
     */
    public static boolean isContainKey(String json, String key) {
        JSONObject jsonObject = JSONObject.parseObject(json);
        return jsonObject.containsKey(key);
    }

    /**
     * JSON 获取特定字段
     */
    public static String getValueByKey(String json, String key) {

        JSONObject jsonObject = JSONObject.parseObject(json);

        return jsonObject.getString(key);
    }

    /**
     * JSON 转Map
     */
    public static Map<String, Object> getMap(String json) {
        //添加 Feature.OrderedField 保证数据的有序性
        return JSONObject.parseObject(json, Feature.OrderedField);
    }

    /**
     * Bean转JSON
     */
    public static <T> String getJSON(T bean) {
        return JSONObject.toJSONString(bean);
    }

    /**
     * File 转Base64
     */
    public static String getBase64(File file) {
        String base64 = null;
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputStream.read(buffer);
            inputStream.close();
            base64 = Base64.encodeToString(buffer, Base64.DEFAULT);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert base64 != null;

        return base64;
    }

    /**
     * File 转Bitmap
     */
    public static Bitmap getBitmap(File file) {
        return BitmapFactory.decodeFile(file.getPath());
    }


    /**
     * 截取字符串
     */
    public static String substring(String s, int start, int finish) {
        return s.substring(start, finish);
    }

    /**
     * 对传入的字符串进行混淆
     *
     * @param s      字符串
     * @param start  开始位置
     * @param finish 结束位置
     */
    public static String obfuscationString(String s, int start, int finish) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i >= start && i < finish) {
                chars[i] = '*';
            }
        }
        return String.valueOf(chars);
    }

    /**
     * 对传入数据根据传入的符号进行截取
     */
    public static String[] splitLocation(String location, String tag) {
        String[] strings = location.split(tag);

        return strings;
    }

    /**
     * 封装多个图片文件
     */
    public static List<MultipartBody.Part> filesToMultipartBodyParts(String key, List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);

            MultipartBody.Part part = MultipartBody.Part.createFormData(key, file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }

    /**
     * 封装单个图片文件
     */
    public static MultipartBody.Part imageFileToMultipartBodyPart(String key, File file) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        return MultipartBody.Part.createFormData(key, file.getName(), requestBody);
    }

    /**
     * 封装多图片带参数请求体
     */
    public static List<MultipartBody.Part> imageAndValueToMultipartBodyPartList(Map<String,File> images,
                                                                                Map<String,String> values){
        List<MultipartBody.Part> parts = new ArrayList<>();

        //封装图片
        String[] imageKeys = images.keySet().toArray(new String[0]);
        for (int i=0;i<images.size();i++){
            MultipartBody.Part imagePart = imageFileToMultipartBodyPart(imageKeys[i],images.get(imageKeys[i]));
            parts.add(imagePart);
        }

        //封装参数
        String[] valueKeys = values.keySet().toArray(new String[0]);
        for (int i=0;i<valueKeys.length;i++){
            MultipartBody.Part valuePart = stringToMultipartBodyPart(valueKeys[i],values.get(valueKeys[i]));
            parts.add(valuePart);
        }

        return parts;
    }

    /**
     * 封装单个文件
     */
    public static MultipartBody.Part fileToMultipartBodyPart(String key, File file) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return MultipartBody.Part.createFormData(key, file.getName(), requestBody);
    }

    /**
     * 封装当个参数文件
     */
    public static MultipartBody.Part stringToMultipartBodyPart(String key, String value) {
        return MultipartBody.Part.createFormData(key, value);
    }

    /**
     * 去除特殊符号
     */
    public static String filtration(String str) {
        String regEx = "[`~!@#$%^&*()+=|{}:;\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？']";
        str = Pattern.compile(regEx).matcher(str).replaceAll("").trim();
        System.out.println("str ======" + str + ".");

        return str;
    }

    /**
     * 去除字符串中空格制表符换行
     */
    public static String replaceBlank(String src) {

        String dest = "";
        if (src != null) {
            Pattern pattern = Pattern.compile("\t|\r|\n|\\s*");
            Matcher matcher = pattern.matcher(src);
            dest = matcher.replaceAll("");
        }

        return dest;
    }

    /**
     * 验证传入字符串是否为空
     */
    public static boolean isStringNONull(String s) {
        return !"".equals(s) && null != s;
    }

    /**
     * 检查数字参数是否正确
     */
    public static boolean isNumCorrect(String num) {
        char[] stringNum = num.toCharArray();
        return stringNum[0] != '0';
    }

    /**
     * 将List转为逗号分割的String字符串
     * Collection<T> list的父类
     */
    public static String listToStringDate(Collection<String> listData) {


        String listString = StringUtils.join(listData, ",");

        return listString;

    }

    /**
     * 检查字符串是否是数字
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            int chr = str.charAt(i);
            if (chr < 48 || chr > 57){
                return false;
            }
        }
        return true;
    }

    /* 将链表序列化为字符串存入json文件中 */
    public static String serilizableForList(Object objList)
            throws IOException {

        String listString = JSON.toJSONString(objList, true);// (maps,CityEntity.class);

        return listString;
    }

    /* 将json文件中的内容读取出来，反序列化为链表 */
    public static <T> List<T> deserilizableForListFromFile(String listString2, Class<T> clazz)
            throws IOException {

        List<T> list2 = JSON.parseArray(listString2, clazz);
        return list2;
    }

    /* 将HashMap序列化为字符串存入json文件中 */
    public static String serilizableForMap(Object objMap)
            throws IOException {

        String listString = JSON.toJSONString(objMap, true);// (maps,CityEntity.class);
        return listString;
    }

    /* 将json文件中的内容读取出来，反序列化为HashMap */
    public static <T, K> HashMap<K, T> deserilizableForMapFromFile(String listString2, Class<T> clazz) throws IOException {

        Map<K, T> map = JSON.parseObject(listString2, new TypeReference<Map<K, T>>() {
        });

        return (HashMap<K, T>) map;
    }

    /**
     * Drawable转换成一个Bitmap
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    private static Bitmap bitmap;

    /**
     * 通过URL获取Bitmap
     */
    public static Bitmap returnBitMap(String url) {
        bitmap = null;
        new Thread(new Runnable() {

            @Override
            public void run() {

                URL imageurl = null;

                try {

                    imageurl = new URL(url);
                } catch (MalformedURLException e) {

                    e.printStackTrace();
                }
                try {

                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;

    }

    /**
     * 返回存储路径
     */
    public static String getCCDMerchantFilePath(String path) {
        return path;
    }

    /**
     * 检查当前sdcard文件夹中是否存在ccd_merchant文件夹
     */
    public static void isCCDMerchantFileExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
    }

    /**
     * 获取系统时间戳
     *
     * @return
     */
    public long getCurTimeLong() {
        long time = System.currentTimeMillis();
        return time;
    }

    /**
     * 获取当前时间
     *
     * @param pattern
     * @return
     */
    public static String getCurDate(String pattern) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date());
    }

    /**
     * 时间戳转换成字符窜
     *
     * @param milSecond
     * @param pattern
     * @return
     */
    public static String getDateToString(long milSecond, String pattern) {
        Date date = new Date(milSecond);
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    /**
     * 将字符串转为时间戳
     *
     * @param dateString
     * @param pattern
     * @return
     */
    public static long getStringToDate(String dateString, String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        try {
            date = dateFormat.parse(dateString);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    /**
     * 返回map指定位置的value
     */
    public static <T> T getMapValue(Map<String, T> dataMap, int position) {

        String[] keys = dataMap.keySet().toArray(new String[0]);
        return dataMap.get(keys[position]);
    }

    /**
     * 验证手机号格式是否正确
     */
    public static boolean confirmPhoneNum(String phone) {
        //宽松验证表达式
        String phoneRegexLoose = "^((1[3-9]))\\d{9}$";
        //相对严格验证表达式
        String phoneRegexPreciseness = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[759]|16[6]))\\d{8}$";

        Pattern pattern = Pattern.compile(phoneRegexLoose);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }
}
